package org.se.scut.pinterest.mina.handler;

import java.util.Date;

import org.apache.mina.core.session.IoSession;
import org.se.scut.hibernate.dao.model.Picture;
import org.se.scut.hibernate.dao.model.PictureType;
import org.se.scut.hibernate.dao.service.PictureServiceImp;
import org.se.scut.hibernate.dao.service.PictureTypeImp;
import org.se.scut.hibernate.dao.service.iface.IPictureService;
import org.se.scut.hibernate.dao.service.iface.IPictureTypeService;
import org.se.scut.pinterest.mina.codec.msg.Message;
import org.se.scut.pinterest.mina.codec.msg.PictureUploadMessage;
import org.se.scut.pinterest.mina.handler.observer.IMessageObserver;
import org.se.scut.pinterest.mina.handler.observer.MessageOperatorType;
import org.se.scut.pinterest.mina.utils.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class PictureUploadHandler implements IMessageObserver {

	private static final Logger LOGGER = LoggerFactory.getLogger(PictureUploadHandler.class);
	private final IPictureService picService = new PictureServiceImp();
	private final PictureTypeImp typeService = new PictureTypeImp();

	
	@Override
	public void onMessageChange(IoSession session, Message msg, MessageOperatorType type) {
		
		String fileName = ((PictureUploadMessage)msg).getFileName();
		int pictureTypeID = ((PictureUploadMessage)msg).getPictureTypeID();
		int ablumID = ((PictureUploadMessage)msg).getAblumID();
		byte[] content = ((PictureUploadMessage)msg).getContent();
		FileUtils.bytesToFile(content, fileName);
		Picture pic = new Picture();
		pic.setContent_length(((PictureUploadMessage)msg).getFileLength());
		pic.setFilePath(FileUtils.bytesToFile(content, fileName));
		pic.setNumOfLove(0);
		pic.setOverView(((PictureUploadMessage)msg).getOverView());
		pic.setCreateTime(new Date());
		pic.setPictureType((PictureType)typeService.find(PictureType.class, pictureTypeID));
		picService.create(pic, ((PictureUploadMessage)msg).getUserID(), ablumID, 0);
		
	}

}
